/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package io.renren.modules.sys.interceptor;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.renren.entity.SysUserTokenEntity;
import io.renren.modules.sys.service.SysUserTokenService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author zyj
 * @email sunlightcs@gmail.com
 * @date 2019.1.9
 */
@Component
public class SysAuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private SysUserTokenService sysUserTokenService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        if(token == null){
            return true;
        }
        if(token.equals("undefined")){
            return true;
        }
        if(token.equals("")){
            return true;
        }
        SysUserTokenEntity sysUserTokenEntity = sysUserTokenService.selectOne(new EntityWrapper<SysUserTokenEntity>().eq("token",token));
        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute("token",token);
        request.setAttribute("userId",sysUserTokenEntity.getUserId());
        return true;
    }
}
